<template>
  <div class="page-setup">
    <div class="page-setup-header">
      <div class="setup-mode">
        <span class="icon iconfont icon-PC" @click="chageModel(1)"></span>
        <span class="icon iconfont icon-shouji" @click="chageModel(2)"></span>
      </div>
      <div class="setup-btn">
        <a-button type="primary" @click="submit">保存</a-button>
      </div>
    </div>

    <DesignerLayout
      v-if="showLayout"
      :lays="layout"
      @layoutUpdatedEvent="layoutUpdatedEvent"
    />

    <div class="page-setup-content">
      <div class="setup-tools">
        <div class="setup-layout">
          <span
            :class="item.icon"
            v-for="(item, i) in layouts"
            :key="i"
            @click="chageLayout(item)"
          ></span>
        </div>
        <div class="setup-row" v-for="(item, i) in components" :key="i">
          <div class="setup-cols">
            <div
              class="cols-item"
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
              draggable="move"
              :attr-key="item.code"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="page-container">
        <div
          class="page-container-center grid"
          :class="model === 1 ? 'pc' : 'phone'"
        >
          <div class="grid-row"></div>
          <div class="grid-row"></div>
          <div class="grid-row"></div>
          <!-- <div v-for="(item, i) in layoutMap" :key="i"></div> -->
          <!-- <div
            class="page-container-row"
            v-for="(item, i) in attrsVal"
            :class="item.autoHeight ? 'flex-1' : ''"
            :key="i"
            :i="i"
            @click="changeCurrentComponent(i)"
            draggable="sort-y"
          >
            <i class="icon iconfont icon-tuozhuai1 tz"></i>
            <div
              class="sh"
              @mousedown="
                (ev) => {
                  ev.stopImmediatePropagation();
                }
              "
            >
              <i class="icon iconfont icon-delete" @click="remove(i)"></i>
              <component :config="item" :is="getComponents(item.componentKey)">
              </component>
            </div>
          </div> -->
        </div>
      </div>
      <div class="page-setup-attrs">
        <div class="page-setup-attrs-header">
          <div class="page-setup-attrs-title">属性{{ currentIndex }}</div>
        </div>
        <div class="page-setup-attrs-content">
          <div v-for="(attrs, i) in attrsVal" :key="i">
            <DesignerAttrsSet
              v-show="i === currentIndex"
              :attrs="allAttrs[i]"
              :key="i"
              @change="
                (val) => {
                  change(i, attrs.componentKey, val);
                }
              "
              ref="attrsRef"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import Drag from "@/utils/drag";
import * as Attrs from "@/utils/attrs";
import layouts from "@/utils/layout";
// import PageComponents from "@/utils/Designer/components";
// import PageTemplate from "@/utils/Designer/page";
import { getComponentsAll } from "@/api/designer/components";
import { setOffPages, getPagesInfo } from "@/api/designer/pages";

// const props = defineProps({
//   project: {
//     type: Object,
//     default: () => {
//       return {};
//     },
//   },
//   url: {
//     type: String,
//     default: "",
//   },
//   name: {
//     type: String,
//     default: "",
//   },
// });

const components = ref([]);
const pageInfo = ref([]);
const route = useRoute();
const attrsRef = ref();

const type = ref("");
const currentIndex = ref(0);
const attrs = ref([]);
const allAttrs = ref([]); // 所有组件配置对象信息
const attrsVal = ref([]); // attrs 值对象信息
const setup = ref([]); // 页面组件排列

/**
 * 遍历所有属性模板
 */
const modules = import.meta.glob("./Template/**/*");
const M = ref({});
Object.keys(modules).forEach(async (key) => {
  const k = key.replace(".vue", "");
  const module = await modules[key]();
  M.value[k] = markRaw(module.default);
});

/**
 *  获取页面信息
 */
const getInfo = async () => {
  const { code, data } = await getPagesInfo({
    id: route.query.id,
  });
  if (code === rescf.codeVal) {
    pageInfo.value = data;
    setup.value = data.setup;
    if (data.components) {
      attrsVal.value = data.components;
      data.components.forEach((a, i) => {
        const o = { ...a };
        Object.keys(o).forEach((k) => {
          console.log(a.componentKey, a, "a.componentKey");
          if (!a.componentKey) return;
          const i2 = Attrs[a.componentKey].findIndex((a) => a.field === k);
          allAttrs.value[i] = [...Attrs[a.componentKey]];
          if (allAttrs.value[i][i2]) {
            allAttrs.value[i][i2].value = o[k];
          }
        });
      });
    }
    // type.value = data.setup[0];
    console.log("setup.value", setup.value);
    console.log("attrsVal.value", attrsVal.value);
    console.log("allAttrs.value", allAttrs.value);
    nextTick(() => {
      type.value = 0;
    });
  }
};

getInfo();

/**
 * 布局
 */
const layout = ref(1);
const showLayout = ref(false);
const layoutMap = ref({});
const chageLayout = (item) => {
  layout.value = item.map;
  showLayout.value = true;
};

/**
 * 布局更新事件
 */
const layoutUpdatedEvent = (val) => {
  layoutMap.value = val;
  console.log("layoutUpdatedEvent", layoutMap.value);
};

/**
 * 获取所有设计器组件
 */
const getComponentsTabs = async () => {
  const { code, data } = await getComponentsAll();
  if (code === rescf.codeVal) {
    components.value = data;
  }
};

getComponentsTabs();

/**
 * 删除组件
 */
const remove = (key) => {
  attrsVal.value.splice(key, 1);
  allAttrs.value.splice(key, 1);
};

/**
 * 切换设计器组件
 */
const changeCurrentComponent = (i) => {
  currentIndex.value = i;
};

/**
 * 显示模式 1pc 2手机
 */
const model = ref(1);

/**
 * 显示模式
 */
const chageModel = (type) => {
  model.value = type;
};

/**
 * 监听属性表单变化
 */
const change = (i, key, val) => {
  if (val.target) return;
  attrsVal.value[i] = { ...val, componentKey: key };
  console.log(attrsVal.value, i, "ooooooooooo");
};

/**
 * 获取属性配置表单
 */
const getAttrs = (key) => {
  if (Attrs[key]) {
    attrs.value = [...Attrs[key]];
    let o = {
      componentKey: key,
    };

    attrs.value.forEach((item) => {
      o[item.field] = item.value;
    });
    attrsVal.value = attrsVal.value.concat(o);
    allAttrs.value = allAttrs.value.concat([attrs.value]);

    console.log(allAttrs, attrsVal, "===11===");
    // attrsVal.value[key] = Attrs[key];
  }
};

/**
 * 获取组件
 */
const getComponents = (key) => {
  console.log(key, "-----key------");
  if (!key) return;
  const path = key.substr(0, 1).toUpperCase() + key.substr(1);
  return M.value[`./Template/${path}`];
};

/**
 * 页面装饰接口
 */
const setOff = async (config) => {
  const { code } = await setOffPages({
    id: route.query.id,
    ...config,
  });
  if (code === rescf.codeVal) {
    // router.push({ path: "/designer/project" });
    message.success("保存成功");
  }
};

/**
 * 属性验证
 */
const validate = () => {
  console.log(attrsRef.value, "--------------attrsRef.value");
  if (attrsRef.value) {
    const els = attrsRef.value.map((item) => {
      return item.validate();
    });
    return Promise.all(els);
  } else {
    return Promise.reject();
  }
};

/**
 * 保存装饰
 */
const submit = async () => {
  const valid = await validate();
  if (valid) {
    setOff({
      project: pageInfo.value.project,
      url: pageInfo.value.url,
      name: pageInfo.value.name,
      components: attrsVal.value,
    });
  }
};

const swap = (i1, i2) => {
  const val = attrsVal.value[i1];
  attrsVal.value[i1] = attrsVal.value[i2];
  attrsVal.value[i2] = val;
};

onMounted(() => {
  /**
   * 初始化拖拽
   */
  new Drag({
    container: ".designer-advertising", // 拖拽元素所在容器className
    targetEl: "page-container", // 拖拽目标元素容器className
    moveEl: "drag-move_style", // 拖拽元素className
    dragEl: "designer", // 拖拽元素属性标识
    scrollEl: "#app",
    end: (el1, el2, sort) => {
      attrs.value = [];
      type.value = el1.getAttribute("attr-key");
      getAttrs(type.value);
      console.log(el2, "type.value");
      if (sort) {
        swap(el1.getAttribute("i") * 1, el2.i);
      }
    },
  });
});
</script>
<style scoped lang="scss">
.page-setup {
  height: 100%;
  color: #fff;
}

.page-setup-header {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid var(--colorBorder);
  height: 58px;
}

.setup-btn {
  width: 405px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 15px;
}

.setup-mode {
  display: flex;
  justify-content: center;
  margin-left: 280px;
  flex: 1;
  height: 100%;
  span {
    margin: 0 10px;
    font-size: 26px;
    padding: 15px 0;
    cursor: pointer;
  }
}

.page-setup-attrs {
  width: 435px;
  border-left: 1px solid var(--colorBorder);
  .page-setup-attrs-title {
    padding: 10px 20px;
    border-bottom: 1px solid var(--colorBorder);
    border-top: 1px solid var(--colorBorder);
    font-weight: bold;
  }
}

.page-setup-content {
  height: calc(100% - 59px);
  display: flex;
}
.setup-tools {
  width: 280px;
  height: 100%;
  border-right: 1px solid var(--colorBorder);

  border-left: 1px solid var(--colorBorder);
  h3 {
    padding: 10px 20px;
    border-bottom: 1px solid var(--colorBorder);
    border-top: 1px solid var(--colorBorder);
  }
  .setup-cols {
    padding: 0 0;
  }
  .cols-item {
    border-right: 1px solid var(--colorBorder);
    border-bottom: 1px solid var(--colorBorder);
    padding: 15px 0;
    text-align: center;
    i {
      font-size: 24px;
    }
  }
}
.flex {
  display: flex;
  flex-wrap: wrap;
}
.flex-1 {
  flex: 1;
}
.page-container {
  height: 100%;
  width: calc(100% - 280px - 435px);
  .page-container-center {
    margin: 0 auto;
    height: 100%;
    width: 100%;
    flex-direction: column;
    display: grid;
    grid-template-columns: 100%;
    grid-template-rows: 200px calc(100% - 200px) ;

    .grid-row {
      border: 1px solid #000;
    }

    &.pc {
      width: 100%;
    }
    &.iphone {
      width: 480px;
    }
  }

  iframe {
    width: 100%;
    height: 100%;
  }
}

.page-container-row {
  position: relative;
  width: 100%;
  .sh {
    height: 100%;
  }
  &:hover .icon-delete {
    display: block;
  }
  &:hover .tz {
    display: block;
  }
  .tz {
    cursor: move;
    position: absolute;
    left: 50%;
    top: 5px;
    z-index: 10;
    font-size: 20px;
    display: none;
  }
  .icon-delete {
    font-size: 20px;
    color: #2c3e50;
    position: absolute;
    right: 10px;
    top: 5px;
    z-index: 10;
    cursor: pointer;
    display: none;
  }
}

.setup-layout {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 58px;
  border-bottom: 1px solid var(--colorBorder);
  cursor: pointer;
  background-color: #e7f5f7;
  .icon {
    font-size: 30px;
    margin: 0 10px;
  }
}
</style>
